package com.example.spring.others;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 如果想要对spring 某个bean进行修改,继承BeanPostProcessor
 * 实例化、依赖注入完毕，在调用显示的初始化之前完成一些定制的初始化任务
 *
 * @author majie
 * @date 2018/6/25.
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * bean 初始化前
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(atomicInteger.getAndIncrement());
        if (bean instanceof Cat) {
            //输出原始属性
            Cat cat = (Cat) bean;
            cat.say();
            return bean;
        }
        return bean;

    }

    /**
     * bean初始化后
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Cat) {
            //修改属性值，并返回
            Cat cat = (Cat) bean;
            cat.setName("hello maomi");
            cat.setAge(3);
            return cat;
        }
        return bean;
    }
}
